package com.rd.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rd.util.ResultModel;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 当访问接口没有权限时，自定义返回结果
 * AccessDeniedHandler 是 Spring Security 中的一个接口，用于处理认证或授权失败的情况。
 * 它定义了以下方法：
 * 当访问被拒绝时，handle该方法将被调用。
 */
@Component
public class RestfulAccessDeniedHandler
implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        ResultModel bean = ResultModel.createByErrorCodeMessage(403,"权限不足，请联系管理员！");
        out.write(new ObjectMapper().writeValueAsString(bean));
        out.flush();
        out.close();
    }
}
